﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;

namespace LaoLuo
{
    /// <summary>
    /// RNGCryptoServiceProvider is used inside
    /// </summary>
    public class RandomProvider
    {
        public static class RandomNumber
        {
            #region Fields

            private static readonly byte[] Randb = new byte[4];
            private static readonly RNGCryptoServiceProvider Rand = new RNGCryptoServiceProvider();

            #endregion

            #region Methods

            /// <summary>
            ///     Generates a positive random number.
            /// </summary>
            private static int Next()
            {
                Rand.GetBytes(Randb);
                int value = BitConverter.ToInt32(Randb, 0);
                return Math.Abs(value);
            }

            /// <summary>
            ///     Generates a positive random number.
            /// </summary>
            public static int Next(int max)
            {
                return Next() % (max + 1);
            }

            /// <summary>
            ///     Generates a positive random number.
            /// </summary>
            public static int Next(int min, int max)
            {
                return Next(max - min) + min;
            }

            #endregion
        }

        public static class RandomText
        {
            #region Method

            /// <summary>
            ///     Generates the random text.
            /// </summary>
            /// <param name="chars">The specified characters.</param>
            /// <param name="count">The number of characters.</param>
            /// <returns>The random text</returns>
            public static string Generate(string chars, int count)
            {
                int lenght = RandomNumber.Next(count, count);
                var output = new StringBuilder(lenght);

                for (int i = 0; i < lenght; i++)
                {
                    int randomIndex = RandomNumber.Next(chars.Length - 1);
                    output.Append(chars[randomIndex]);
                }

                return output.ToString();
            }

            #endregion
        }
    }
}
